package com.hlj.ncp.warehouse.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.hlj.ncp.common.core.domain.AjaxResult;
import com.hlj.ncp.warehouse.entity.Stock;
import com.hlj.ncp.warehouse.service.IStockService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 库存信息操作处理
 */
@Controller
@RequestMapping("/stock")
public class StockController {
    @Autowired
    private IStockService stockService;

    /**
     * 库存管理页面
     */
    @GetMapping("/index")
    public String index() {
        return "stock/index";
    }

    /**
     * 获取库存列表
     */
    @PreAuthorize("hasAuthority('warehouse:stock:list')")
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult list(Stock stock) {
        List<Stock> list = stockService.selectStockList(stock);
        return AjaxResult.success(list);
    }

    /**
     * 获取库存详细信息
     */
    @PreAuthorize("hasAuthority('warehouse:stock:query')")
    @GetMapping(value = "/{stockId}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("stockId") Long stockId) {
        return AjaxResult.success(stockService.selectStockById(stockId));
    }

    /**
     * 新增库存
     */
    @PreAuthorize("hasAuthority('warehouse:stock:add')")
    @PostMapping
    @ResponseBody
    public AjaxResult add(@RequestBody Stock stock) {
        return AjaxResult.success(stockService.insertStock(stock));
    }

    /**
     * 修改库存
     */
    @PreAuthorize("hasAuthority('warehouse:stock:edit')")
    @PutMapping
    @ResponseBody
    public AjaxResult edit(@RequestBody Stock stock) {
        return AjaxResult.success(stockService.updateStock(stock));
    }

    /**
     * 删除库存
     */
    @PreAuthorize("hasAuthority('warehouse:stock:remove')")
    @DeleteMapping("/{stockIds}")
    @ResponseBody
    public AjaxResult remove(@PathVariable Long[] stockIds) {
        return AjaxResult.success(stockService.deleteStockByIds(stockIds));
    }
    
    /**
     * 出库操作
     */
    @PreAuthorize("hasAuthority('warehouse:stock:out')")
    @PostMapping("/out")
    @ResponseBody
    public AjaxResult outStock(@RequestBody Map<String, Object> params) {
        Long stockId = Long.valueOf(params.get("stockId").toString());
        Integer quantity = Integer.valueOf(params.get("quantity").toString());
        String reason = (String) params.get("reason");
        String remark = (String) params.get("remark");
        
        return AjaxResult.success(stockService.outStock(stockId, quantity, reason, remark));
    }
    
    /**
     * 获取库存统计数据
     */
    @GetMapping("/stats")
    @ResponseBody
    public AjaxResult getStockStats() {
        long totalCount = stockService.count();
        Double totalValue = stockService.getTotalStockValue();
        long lowStockCount = stockService.getLowStockCount();
        long outOfStockCount = stockService.getOutOfStockCount();
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", totalCount);
        stats.put("totalValue", totalValue != null ? totalValue : 0.0);
        stats.put("lowStockCount", lowStockCount);
        stats.put("outOfStockCount", outOfStockCount);
        
        return AjaxResult.success(stats);
    }
    
    /**
     * 获取预警库存数量
     */
    @GetMapping("/alert/count")
    @ResponseBody
    public AjaxResult getAlertCount() {
        long lowStockCount = stockService.getLowStockCount();
        return AjaxResult.success(lowStockCount);
    }
    
    /**
     * 导出库存数据
     */
    @PreAuthorize("hasAuthority('warehouse:stock:export')")
    @GetMapping("/export")
    @ResponseBody
    public AjaxResult export(Stock stock) {
        List<Stock> list = stockService.selectStockList(stock);
        // 这里只返回数据，实际导出功能需要更多处理
        return AjaxResult.success(list);
    }

    /**
     * 获取库存预警列表
     */
    @GetMapping("/alerts")
    @ResponseBody
    public AjaxResult getStockAlerts(@RequestParam(required = false, defaultValue = "5") Integer limit) {
        // 模拟库存预警数据
        List<Map<String, Object>> alertList = new ArrayList<>();
        
        // 模拟产品和仓库数据
        String[] productNames = {"有机花菜", "新鲜土豆", "红富士苹果", "黄瓜", "西红柿", "胡萝卜", "大白菜", "青椒"};
        String[] warehouseNames = {"主仓库", "冷藏仓库", "蔬菜仓库", "水果仓库", "北区仓库"};
        String[] units = {"公斤", "箱", "件", "包"};
        
        Random random = new Random();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        for (int i = 0; i < limit; i++) {
            Map<String, Object> alert = new HashMap<>();
            
            int productIndex = random.nextInt(productNames.length);
            String productName = productNames[productIndex];
            String productCode = "P" + (10000 + productIndex);
            
            alert.put("stockId", 1000 + i);
            alert.put("productId", 100 + productIndex);
            alert.put("productName", productName);
            alert.put("productCode", productCode);
            alert.put("warehouseName", warehouseNames[random.nextInt(warehouseNames.length)]);
            
            // 生成预警库存数据
            int currentQuantity = random.nextInt(10);
            int warningQuantity = 10 + random.nextInt(10);
            String unit = units[random.nextInt(units.length)];
            
            alert.put("quantity", currentQuantity);
            alert.put("warningQuantity", warningQuantity);
            alert.put("unit", unit);
            
            // 预警级别：1-轻微，2-中度，3-严重（缺货）
            int alertLevel = (currentQuantity == 0) ? 3 : (currentQuantity < warningQuantity / 2) ? 2 : 1;
            alert.put("alertLevel", alertLevel);
            
            // 最后更新时间
            LocalDateTime updateTime = LocalDateTime.now().minusDays(random.nextInt(7));
            alert.put("updateTime", updateTime.format(formatter));
            
            alertList.add(alert);
        }
        
        return AjaxResult.success(alertList);
    }
} 